package com.yksj.healthtalk.ui.home;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshExpandableListView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.yksj.healthtalk.adapter.MySalonListExpandableAdapter;
import com.yksj.healthtalk.adapter.MySalonListExpandableAdapter.OnClickDeleteListener;
import com.yksj.healthtalk.adapter.MySalonListExpandableAdapter.OnPayClickListener;
import com.yksj.healthtalk.adapter.MySalonListExpandableAdapter.onClickGroupHeadListener;
import com.yksj.healthtalk.adapter.MySalonListExpandableAdapter.onClickSalonAttentionListener;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SalonPayActivity;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.salon.SalonInformationActivity;
import com.yksj.healthtalk.ui.salon.SalonReadSelf;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.CollectUtils;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * @author Administrator 我的话题
 */
public class MySalonListFragment extends Fragment implements OnClickListener,
		OnGroupClickListener, OnChildClickListener, onClickGroupHeadListener,
		OnBuyTicketHandlerListener, OnPayClickListener, OnClickDeleteListener, onClickSalonAttentionListener, OnRefreshListener<ExpandableListView> {

	private MySalonListExpandableAdapter adapter;
	public String expand_group_text;// 该组的组名
	private AppData mAppData;
	private GroupInfoEntity cacheGroupInfoEntity;
	private ExpandableListView group_expand;
	private PullToRefreshExpandableListView refreshView;
	private View headerView;
	private ChatUserHelper chatUserHelper;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					String id = intent.getStringExtra("senderId");
					if (mAppData.getInterestGroupIdList().contains(id)) {
						setAdapter();
					}
				}
			}else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getActivity(), R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestUnfollowToSalonResult(getActivity(),cacheGroupInfoEntity, mAppData, chatUserHelper);
					adapter.notifyDataSetChanged();
				}
			} else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getActivity(), R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestAttentionToSalonResult(getActivity(),cacheGroupInfoEntity, mAppData, chatUserHelper);
					adapter.notifyDataSetChanged();
				}
			}
			
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.myfriend_fragment_layout, null);
		chatUserHelper = ChatUserHelper.getInstance();
		mAppData = HTalkApplication.getAppData();
		queryInfolay();

		refreshView = (PullToRefreshExpandableListView) v
				.findViewById(R.id.hall);
		refreshView.setOnRefreshListener(this);
		
		group_expand = (ExpandableListView) refreshView.getRefreshableView();
		
		headerView = LayoutInflater.from(getActivity()).inflate(R.layout.pull_to_refresh_header_edit, null);
		group_expand.addHeaderView(headerView);
		group_expand.setGroupIndicator(null);
		group_expand.setOnChildClickListener(this);
		group_expand.setOnGroupClickListener(this);
		return v;
	}

	private void getGroupData(
			final PullToRefreshBase<ExpandableListView> refreshView) {
		HttpRestClient.doHttpFindGroupsList(SmartFoxClient.getLoginUserId(), new ObjectHttpResponseHandler() {
			@Override
			public Object onParseResponse(String cotent) {
				mAppData.getCreatedGroupIdList().clear();
				mAppData.getbuyFailureGroupIdList().clear();
				mAppData.getInterestGroupIdList().clear();
				mAppData.getMyBoughtGroupIdList().clear();
				mAppData.getMyBoughtHisGroupIdList().clear();
				AppData appData = HTalkApplication.getAppData();
				JsonParseUtils.LoginInitSalon(getActivity(), cotent, appData,false);
				return null;
			}

			@Override
			public void onSuccess(int statusCode, Object response) {
				setAdapter();
				super.onSuccess(statusCode, response);
			}

			@Override
			public void onFinish() {
				refreshView.onRefreshComplete();
				super.onFinish();
			}
		});
	}

	public static Fragment getInstance() {
		MySalonListFragment fragment = new MySalonListFragment();
		Bundle args = new Bundle();
		args.putBoolean("isInCollectionActivity", true);
		fragment.setArguments(args);
		return fragment;

	}

	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		getActivity().registerReceiver(receiver, filter);
		if (refreshView != null) {
			refreshView.setRefreshing();
			getGroupData(refreshView);
		}
		super.onStart();
	}

	@Override
	public void onStop() {
		getActivity().unregisterReceiver(receiver);
		super.onStop();
	}

	private void setAdapter() {
		if (adapter == null) {
			adapter = new MySalonListExpandableAdapter(getActivity(), this);
			adapter.setIntoInfoListener(this);
			group_expand.setAdapter(adapter);
			adapter.setonClickSalonAttentionListener(this);
			adapter.setonClickGroupHeadListener(this);
			for (int i = 0; i < adapter.getGroupCount(); i++) {
				group_expand.expandGroup(i);
			}
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long viewId) {
		AppData appData = HTalkApplication.getAppData();
		if (groupPosition == 0) {
			cacheGroupInfoEntity = appData.getGroupInfoEntity(mAppData.getInterestGroupIdList().get(childPosition));
		} else if (groupPosition == 1) {
			cacheGroupInfoEntity = appData.getGroupInfoEntity(mAppData.getCreatedGroupIdList().get(childPosition));
		} else if (groupPosition == 2) {
			cacheGroupInfoEntity =appData.getGroupInfoEntity(mAppData.getMyBoughtGroupIdList().get(childPosition));
		} else if (groupPosition == 3) {
			cacheGroupInfoEntity =appData.getGroupInfoEntity(mAppData.getbuyFailureGroupIdList().get(
									childPosition));
		} else if (groupPosition == 4) {
			cacheGroupInfoEntity =appData.getGroupInfoEntity(mAppData.getMyBoughtHisGroupIdList().get(childPosition));
		}
		SalonHttpUtil.onItemClick(getActivity(), this,getChildFragmentManager(), cacheGroupInfoEntity, true);
		return true;
	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		if(groupPosition==3){
			Intent intent=new Intent(getActivity(),MySalonMoreActivity.class);
			getActivity().startActivity(intent);
			return true;
		}else{
			return false;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.refresh_header_btn:
			break;
		}
	}

	private void queryInfolay() {
		chatUserHelper.queryGroupInfo(getActivity(), mAppData, SmartFoxClient.getLoginUserId());
	}

	@Override
	public void onClickFriendHead(GroupInfoEntity entity) {
		if (entity.getCreateCustomerID().equals(SmartFoxClient.getLoginUserId())) {
			Intent intent = new Intent();
			intent.setClass(getActivity(), SalonReadSelf.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		} else {
			Intent intent = new Intent();
			intent.setClass(getActivity(), SalonInformationActivity.class);
			Bundle bundle = new Bundle();
			intent.putExtra("id", entity.getId());
			bundle.putInt("position", -1);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}

	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		if ("0".equals(state)) {
		} else if ("-1".equals(state)) {
			ToastUtil.showShort(getActivity(), "服务器出错");
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(getActivity(), ChatActivity.class);
			getActivity().startActivity(intent1);
			if (mAppData.getLatelyGroupIdList().contains(entity.getId())) {
				mAppData.getLatelyGroupIdList().remove(entity.getId());
			}
			mAppData.getLatelyGroupIdList().add(0, entity.getId());
			mAppData.updateCacheInfomation(entity);
			CollectUtils.updateGroupRecent(chatUserHelper, entity,SmartFoxClient.getLoginUserId());
		}
	}

	@Override
	public void OnPayClick(String payId) {
		Intent intent = new Intent(getActivity(), SalonPayActivity.class);
		intent.putExtra("payId", payId);
		startActivity(intent);
	}

	@Override
	public void OnClickDelete(final GroupInfoEntity entity, String orderId) {
		// DeleteGroupOrder?ORDERID
		HttpRestClient.doHttpDeleteOrder(orderId,
				new AsyncHttpResponseHandler(getActivity()) {
					@Override
					public void onSuccess(int statusCode, String content) {
						if (content.equalsIgnoreCase("Y")) {
							ToastUtil.showShort(getActivity(), "删除话题订单成功");
							if (refreshView != null) {
								refreshView.setRefreshing();
								getGroupData(refreshView);
							}
						} else {
							ToastUtil.showShort(getActivity(), "删除话题订单失败");
						}
						super.onSuccess(statusCode, content);
					}
				});
	}

	@Override
	public void onSalonAttentionClick(View v, GroupInfoEntity mSalonName,
			int positon) {
		cacheGroupInfoEntity = SalonHttpUtil.requestAttOrUnfollowToSalon(getActivity(),mSalonName);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
		getGroupData(refreshView);
	}
}
